package com.rc.saas.mini.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 生成中电联二维码链接
 * 格式：hlht://19000391.914401153/
 * Created by sven on 2018-05-29
 */
public class HlhtQrCodeUtils {
    private static Logger logger = LoggerFactory.getLogger(HlhtQrCodeUtils.class);
    //互联互通枪号二维码前缀
    private static String prefix = "hlht://";
    // 运营商标识（OperatorID）/组织机构代码(企业名称，营业执照)
    //private static String OperatorID = ".914401153/";
    private static final String OperatorIdTemp = ".{0}/";

    /**
     * https://mini.jin-zhuang.cn/jinzhuang-saas-mini/resource/914401153/115344000051
     * https://mini.jin-zhuang.cn/jinzhuang-saas-mini/resource  固定前缀
     * /914401153   运营商编号
     * /115344000051  枪号
     */
    //瑞晨云小程序二维码
    public static final String regMiniQcode = "https://mini.jin-zhuang.cn/jinzhuang-saas-mini/resource/(\\w+)/(\\w+)";
    public static final String myselfQcode = "/open/qrcode/(\\S+)";

    /**
     * 生成中电联二维码链接
     *
     * @param tenantCode
     * @param epNo
     * @return
     */
    public static String createCecQRCode(String tenantCode, String epNo) {
        tenantCode = MessageFormat.format(OperatorIdTemp, tenantCode);

        if (StringUtils.isNotBlank(epNo)) {
            String uri = prefix + epNo + tenantCode;
            logger.info("QrCodeUtils.createCecQRCode:{},:{}", uri);

            return uri;
        } else {
            return null;
        }
    }


    public static String parserQrCode(String qrCode) {
        Pattern pattern = Pattern.compile(myselfQcode.trim());
        Matcher matcher = pattern.matcher(qrCode);
        if (matcher.find()) {
            return matcher.group((1));
        } else {
            //解析失败直接做枪号
            return qrCode;
        }
    }


    /**
     * 从中电联二维码链接返回枪号
     *
     * @param tenantCode
     * @param scanQRCode
     * @return
     */
    public static String getGunNoFromStdQrCode(String tenantCode, String scanQRCode) {
        if (StringUtils.isBlank(scanQRCode)) {
            return null;
        } else {
            tenantCode = MessageFormat.format(OperatorIdTemp, tenantCode);

            String startToken = prefix;
            String endToken = tenantCode;

            String gunNo = StringUtils.substringBetween(scanQRCode, startToken, endToken);

            //解析小程序二维码
            if (gunNo == null) {
                gunNo = parserSaasMiniQrCode(tenantCode, scanQRCode);
            }

            logger.info("QrCodeUtils.getGunNoFromCecQrCode:{},:{}", scanQRCode, gunNo);
            return gunNo;
        }
    }


    /**
     * saas内互联运营商小程序枪二维码解析
     *
     * @return 枪编号
     */
    public static String parserSaasMiniQrCode(String tenantCode, String qrCode) {
        Pattern pattern = Pattern.compile(regMiniQcode);
        Matcher matcher = pattern.matcher(qrCode);
        if (matcher.find()) {
            //System.out.println(matcher.group(2));
            //运营商编号与解析一致
            if (tenantCode.equals(matcher.group((1)))) {
                return matcher.group(2);
            }
        }
        return null;
    }

    /**
     * 从非中电联二维码链接返回枪号
     *
     * @param regPattern
     * @param scanQRCode
     * @return
     */
    public static String getGunNoFromPattern(String regPattern, String scanQRCode) {
        if (StringUtils.isBlank(scanQRCode)) {
            return null;
        }
        if (StringUtils.isBlank(regPattern)) {
            return null;
        }
        Pattern pattern = Pattern.compile(regPattern.trim());
        Matcher matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            logger.info("QrCodeUtils.getGunNoFromPattern regPattern:{},{},:{}", regPattern, scanQRCode, matcher.group(1).replaceAll("-", "").replaceAll("AC", ""));

            return matcher.group(1).replaceAll("-", "").replaceAll("AC", "");
        } else {
            return null;
        }
    }


    /**
     * 从非中电联二维码链接返回枪号(66专用)
     *
     * @return
     */
    public static String getGunNoFrom66(String regPattern, String scanQRCode) {
        if (StringUtils.isBlank(scanQRCode)) {
            return null;
        }
        if (StringUtils.isBlank(regPattern)) {
            return null;
        }
        Pattern pattern = Pattern.compile(regPattern.trim());
        Matcher matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            logger.info("QrCodeUtils.getGunNoFromPattern regPattern:{},{},:{}", regPattern, scanQRCode, matcher.group(1).replaceAll("-", "").replaceAll("AC", ""));
            String gunNo = matcher.group(1).replaceAll("-", "");
            if (gunNo != null && gunNo.length() >= 9) {
                gunNo = gunNo.substring(2);
            }

            return gunNo;
        } else {
            return null;
        }
    }

    /**
     * 从非中电联二维码链接返回枪号(致联专用)
     *
     * @return
     */
    public static String getGunNoFromZL(String scanQRCode) {
        //String qr = "https://zl-c.cn/180100075504110003/01";
        //String qr = "https://zl-c.cn/18010007550411000301";
        //String qr = "https://zl-c.cn?treminal_number=180100075504110003&gun_number=01";
        if (StringUtils.isBlank(scanQRCode)) {
            return null;
        }
        String reg = "zl-c.cn/(\\S+)/(\\S+)";

        Pattern pattern = Pattern.compile(reg.trim());
        Matcher matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            return matcher.group(1) + "_" + Integer.parseInt(matcher.group(2));
        }
        reg = "zl-c.cn/(\\S+)";
        pattern = Pattern.compile(reg.trim());
        matcher = pattern.matcher(scanQRCode);

        if (matcher.find()) {
            return matcher.group(1).substring(0, matcher.group(1).length() - 1) + "_" + Integer.parseInt(matcher.group(1).substring(matcher.group(1).length() - 2));
        }
        reg = "treminal_number=(\\S+)&gun_number=(\\S+)";
        pattern = Pattern.compile(reg.trim());
        matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            return matcher.group(1) + "_" + Integer.parseInt(matcher.group(2));
        }
        return null;
    }

    /**
     * 从非中电联二维码链接返回枪号(星充专用)
     * 例如：
     * 终端编号：10004451
     * 转换成互联互通编号（ConnectorID）后为：
     * 11000000000000010004451000
     * 终端编号：1012081501
     * 互联互通编号（ConnectorID）：
     * 12000000000000010120815001
     * 120000000000000101208150001
     * 桩编号为10位的转换时是12开头，转换为枪号的时候我们取前8位，枪编号的后三位中第一个0目前都是默认的，是为了以后做扩展，枪编号的最后两位设置的是枪号。
     * //String qr = "https://qrcode.starcharge.com/#/10050638";
     * //String qr = "https://qrcode.starcharge.com/#/1012081501;
     * //String qr = "https://qrcode.starcharge.com/r#/{stubId};
     *
     * @return
     */
    public static String getGunNoFromXC(String scanQRCode) {
        if (StringUtils.isBlank(scanQRCode)) {
            return null;
        }

        String reg = "https://qrcode.starcharge.com/#/(\\S+)";
        Pattern pattern = Pattern.compile(reg.trim());
        Matcher matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            if (matcher.group(1).length() == 8) {
                return "110000000000000" + matcher.group(1) + "000";
            }
            if (matcher.group(1).length() == 10) {
                return "120000000000000" + matcher.group(1).substring(0, matcher.group(1).length() - 2) + "0" + matcher.group(1).substring(matcher.group(1).length() - 2);
            }
        }
        reg = "https://qrcode.starcharge.com/r#/(\\S+)";
        pattern = Pattern.compile(reg.trim());
        matcher = pattern.matcher(scanQRCode);
        if (matcher.find()) {
            if (matcher.group(1).length() == 8) {
                return "110000000000000" + matcher.group(1) + "000";
            }
            if (matcher.group(1).length() == 10) {
                return "120000000000000" + matcher.group(1).substring(0, matcher.group(1).length() - 2) + "0" + matcher.group(1).substring(matcher.group(1).length() - 2);
            }
        }
        return null;
    }

    public static void main(String[] args) {
        //String uri = createCecQRCode("198222855", "19000391");
        //System.out.println("createCecQRCode:" + uri);
        //System.out.println("getEpnoFromCecQrCode:" + getGunNoFromCecQrCode("198222855", uri));
        //String reg = "\\\\?data=(\\S+)";
        //
        //String gunNo = null;
        //String reg = "zl-c.cn/(\\S+)/(\\S+)";
        ////String qr = "https://zl-c.cn/180100075504110003/01";
        ////String qr = "https://zl-c.cn/18010007550411000301";
        //String qr = "https://zl-c.cn?treminal_number=180100075504110003&gun_number=01";
        //Pattern pattern = Pattern.compile(reg.trim());
        //Matcher matcher = pattern.matcher(qr);
        //if (matcher.find()) {
        //    System.out.println(matcher.group(1) + "_" + Integer.parseInt(matcher.group(2)));
        //}
        //
        //if (gunNo == null) {
        //    reg = "zl-c.cn/(\\S+)";
        //    pattern = Pattern.compile(reg.trim());
        //    matcher = pattern.matcher(qr);
        //
        //    if (matcher.find()) {
        //        gunNo = matcher.group(1).substring(0, matcher.group(1).length() - 1) + "_" + Integer.parseInt(matcher.group(1).substring(matcher.group(1).length() - 2));
        //    }
        //}
        //if (gunNo == null) {
        //    reg = "treminal_number=(\\S+)&gun_number=(\\S+)";
        //    pattern = Pattern.compile(reg.trim());
        //    matcher = pattern.matcher(qr);
        //    if (matcher.find()) {
        //        gunNo = matcher.group(1) + "_" + Integer.parseInt(matcher.group(2));
        //    }
        //}


        System.out.println(parserQrCode("http://xxxx.233333333333/open/qrcode/4401001300502"));
        System.out.println(parserQrCode("4401001300502"));
        System.out.println(parserQrCode("http://xxxx.233333333333/open/qrcode/4401001300502-Z-8"));
        System.out.println(parserQrCode("4401001300502-Z-8"));
    }
}
